#include <windows.h>
#include <stdio.h>
#include "tools.h"
#include "image.h"
#include "data.h"
#include "api.h"

#define NROREADERS 2

IMAGEREADER imageReader[NROREADERS]={
	{"bmp", bmpReader},
	{"png", pngReader}
};

PDATA dataCreate(){
	NEW_DATA(DATA);
	data->config = dataLoadConfig();
	data->image = imageCreate(100, 100);
	data->scale = 10;
	data->colorBorder = 0x0000FF;
	data->colorInk = 0x000000;
	data->colorPainter = 0xFF0000;
	data->colorPaper = 0xFFFFFF;
	return data;
}

void dataFreeData(PDATA data){
	dataSaveConfig(data->config);
	imageDelete(data->image);
	apiFree(data->config);
	FREE_DATA();
}

PCONFIG dataLoadConfig(){
	FILE *fconfig = fopen("minerva.cfg", "rb");
	PCONFIG config = (PCONFIG)apiNew(sizeof(CONFIG));
	if (fconfig){
		fread(config, sizeof(CONFIG), 1, fconfig);
		toolLoadConfiguration(fconfig);
		fclose(fconfig);
	}else{
		GetCurrentDirectory(300, config->currentDir);
		GetCurrentDirectory(300, config->paletteDir);
		GetCurrentDirectory(300, config->applicationDir);
		config->windx = 500;
		config->windy = 400;
		config->isMaximized = TRUE;
	}
	return config;
}

void dataSaveConfig(PCONFIG config){
	SetCurrentDirectory(config->applicationDir);
	FILE *fconfig = fopen("minerva.cfg", "wb+");
	fwrite(config, sizeof(CONFIG), 1, fconfig);
	toolSaveConfiguration(fconfig);
	fclose(fconfig);
}

char *dataFileExtension(char *fileName){
	int i = strlen(fileName);
	char *ptr = fileName + i;
	for(;i>=0;i--){
		ptr--;
		if (*ptr=='.'){
			break;
		}
	}
	if (i>0){
		return ptr+1;
	}
	return NULL;
}

IMAGE_CALLBACK dataDetermineReader(char *fileName){
	char *ptr = dataFileExtension(fileName);
	if (ptr){
		int i;
		for(i=0;i<NROREADERS;i++){
			if (!stricmp(ptr,imageReader[i].extension)){
				return imageReader[i].reader;
			}
		}
	}
	return NULL;
}

COLORREF dataGetColor(PDATA data, int x, int y){
	if (x<0 || y<0 || x>=data->image->dx || y>=data->image->dy){
		return 0xFFFFFFFF;
	}
	int offset = data->image->line*((data->image->dy - 1) - y) + x*3;
	data->xyOffset = offset;
	PBYTE ptr = data->image->mem + offset;
	return RGB(ptr[2], ptr[1], ptr[0]);
}

void dataSetColor(PDATA data, COLORREF color){
	PBYTE ptr = data->image->mem + data->xyOffset;
	*ptr++ = GetBValue(color);
	*ptr++ = GetGValue(color);
	*ptr = GetRValue(color);
}